import '../public/index'
import url from '../data/url'
import request from '../data/request'
import {header} from '../data/config'
import {getUrlParam} from '../data/util'

import {bank as valid_bank} from '../data/validate'

const base = url.base,
  addDeveloper = request.editDeveloperManage,
  getBankList = request.getBankList

// 页面标题
const title = '清算银行信息',
  action = '添加';

let id = getUrlParam('id')

const app = new Vue({
  // el: '#app',
  data: {
    saveBankInfo: {
      idStr: null,
      upClearBankCode: null,
      clearBankCode: null,
      name: null,
      bankCode: null,
      bankBranch: null
    }
  },
  created: function () {
    this.getBankInfo()
  },
  methods: {
    getBankInfo() {
      let thisApp = this
      $.ajax({
        type: "POST",
        url: base + '/clearBankMappingInfo/v1/modify.json',
        dataType: "json",
        data: {id: id},
        headers: {
          myToken: Cookies.get('myToken')
        },
      }).then(res => {
        let result = res.object
        thisApp.saveBankInfo.idStr = result.idStr
        thisApp.saveBankInfo.upClearBankCode = result.upClearBankCode
        thisApp.saveBankInfo.clearBankCode = result.clearBankCode
        thisApp.saveBankInfo.name = result.name
        thisApp.saveBankInfo.bankCode = result.bankCode
        thisApp.saveBankInfo.bankBranch = result.bankBranch
        thisApp.renderBankInfo(result)
      })
    },
    renderBankInfo(res) {
      $('#msg-id').text(res.idStr)
      $('#msg-upClearBankCode').val(res.upClearBankCode)
      $('#msg-clearBankCode').val(res.clearBankCode)
      $('#msg-name').val(res.name)
      $('#msg-bankCode').val(res.bankCode)
      $('#msg-bankBranch').val(res.bankBranch)
    }
  }
})

valid()

function valid() {

  let form_valid,
    $form = $('#form')

  $.validator.setDefaults({ // 只能放在validate规则配置之前
  })

  // 验证
  form_valid = $form.validate({
    errorPlacement: function (error, element) {
      error.appendTo(element.parents('.col-xs-24'))
    },
    rules: {
      bankCode: {
        required: true
      },
      name: {
        required: true
      },
      bankBranch: {
        required: true
      },
      clearBankCode: {
        required: true
      },
      upClearBankCode: {
        required: true
      }
    }
  })

}

$('#submit-form').on('click', () => {
  let formData = $('#form').serializeObject()
  if (id) {
    formData = Object.assign({}, formData, {id: id})
  }
  $.ajax({
    headers: header,
    url: base + '/clearBankMappingInfo/v1/save.json',
    type: 'POST',
    data: formData
  }).then(res => {
    if (res.code === 0) {
      location.href = './index.html'
    }
  })
})
